package com.atguigu.gmall.auth.service;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.common.utils.RsaUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.apache.http.auth.AUTH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    GmallUmsClient gmallUmsClient;
    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        //远程调用接口，确认用户名和密码
        ResponseVo<UserEntity> userEntityResponseVo = gmallUmsClient.queryUser(loginName, password);
        UserEntity userEntity = userEntityResponseVo.getData();
        if (userEntity==null){
            throw new AuthException("您输入的账号或密码有误！");
        }

        //生成一个载荷
        Map<String,Object> map  = new HashMap<>();
        map.put("username",userEntity.getUsername());
        map.put("id",userEntity.getId());
        //防止盗用，获取用户的ip地址
        String ipAddress = IpUtils.getIpAddressAtService(request);
        map.put("ip",ipAddress);
        //生成jwt
        try {
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire()*60 );

            //放入cookie
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token, jwtProperties.getExpire()*60);

            //生成昵称
            CookieUtils.setCookie(request,response,jwtProperties.getUnick(),userEntity.getNickname(),jwtProperties.getExpire()*60);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
